package controllers

import (
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	"nspel/entity"
	"nspel/model"
	"nspel/nspel"
	"nspel/util"
)

type ProvinceController struct {
	beego.Controller
}

func (c *ProvinceController) GetProvinceSelect() {
	countryId, err := c.GetInt64("country-id")
	province := new(entity.Province)
	var provinces []entity.Province
	if err == nil {
		provinces, err = province.SelectAllByCountryId(countryId)
	} else {
		provinces, err = province.SelectAll()
	}
	if err != nil {
		if err == orm.ErrNoRows {
			c.Data["json"] = model.GetProvinceSelectRes{}
		} else {
			nspel.Error(err)
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		}
	} else {
		res := model.GetProvinceSelectRes{RetCode: 0}
		res.Province = make([]model.ProvinceSelect, len(provinces))
		for i := 0; i < len(res.Province); i++ {
			res.Province[i].Id = provinces[i].Id
			res.Province[i].Value = provinces[i].Name
		}
		c.Data["json"] = res
	}
	c.ServeJSON()
}

func (c *ProvinceController) GetIndexMap() {
	defer c.ServeJSON()
	province := new(entity.Province)
	provinces, err := province.SelectAll()
	if err != nil {
		nspel.Error(err)
		c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
		return
	}
	res := model.GetIndexMapRes{RetCode: 0}
	res.MapList = make([]model.MapList, len(provinces))
	area := new(entity.Area)
	school := new(entity.School)
	for i := 0; i < len(provinces); i++ {
		res.MapList[i].Name = provinces[i].Name
		util.TransProvinceName(&res.MapList[i].Name)
		count, err := area.SelectCountByProvinceIdIsExperiment(provinces[i].Id, true)
		if err != nil {
			nspel.Error(err)
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			return
		}
		res.MapList[i].Value[0] = count
		count, err = school.SelectCountByProvinceId(provinces[i].Id)
		if err != nil {
			nspel.Error(err)
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			return
		}
		res.MapList[i].Value[1] = count
		count, err = school.SelectCountByProvinceIdIsStandout(provinces[i].Id, true)
		if err != nil {
			nspel.Error(err)
			c.Data["json"] = model.ErrorRes{RetCode: 2, Msg: "服务器运行错误"}
			return
		}
		res.MapList[i].Value[2] = count
	}
	c.Data["json"] = res
}
